<template>
    <div class="avatar">
        <div class="header" @click="back">返回</div>
        <div class="name">
            <input type="text" v-model="old_name" @input="setUserName" />
        </div>
        <div>
            <!-- 保存 -->
            <button @click="modNameFunc">保存新昵称</button>
        </div>
    </div>
</template>

<script lang="ts" setup>
// 导入Vue相关的API
import { ref, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { showToast } from "vant";
import { useUserInfo } from "../../store/user";
// 导入上传图片/保存图片的API
import { upLoadImg, saveImg, deleteImg, getAvatorNickName, modUserName } from "../../api/index";
// 记录图片路径

const store = useUserInfo();

let user_avator = ref("");
// let user_nickname = ref("");
// 记录旧的头像
let old_user_avator = ref("");
let preview_user_avator = ref("");
let isPreview = ref(false);
// 获取token信息
let token = store.$state.token;

let old_name = ref(store.$state.user_nick_name);

const setUserName = ($event) => {
    old_name.value = $event.currentTarget.value;
    // console.log($event.currentTarget.value);
};

const modNameFunc = () => {
    let user_id = store.$state.user_id;
    let user_nick_name = old_name.value;
    // console.log(user_id, user_nick_name);

    modUserName({ user_nick_name, user_id }).then((res: any) => {
        // console.log(res);
        if (res.code == 200) {
            store.$state.user_nick_name = user_nick_name;
            if (localStorage.getItem("user_info")) {
                let user_info = JSON.parse(localStorage.getItem("user_info"));
                user_info.user_nick_name = user_nick_name;
                localStorage.setItem("user_info", JSON.stringify(user_info));
            }
            showToast(res.msg);
            history.back();
        }
    });
};

//
const back = () => {
    history.back();
};
</script>

<style lang="scss">
.avatar {
    padding: 50px 0;
    width: 100%;
    background: #f0f0f0;
    height: 667px;
    text-align: center;

    .header {
        position: absolute;
        top: 0;
        padding: 5px 5px;
        font-size: 14px;
        color: #353535;
    }
    .name {
        input {
            width: 50%;
            padding: 7px 7px;
            outline: 0;
            border: 0;
            border-radius: 5px;
        }
    }
    button {
        margin-top: 20px;
        padding: 5px 0;
        width: 50%;
        border: 1px solid #353535;
        background: #353535;
        color: #fff;
        font-size: 16px;
        border-radius: 5px;
    }
}
</style>
